import axios from 'axios'

// 替换为你的AK和SK
const ACCESS_KEY = 'JA5xwhtdXpVjlUAWBASjclqF';
const SECRET_KEY = 'XPYUb5dWV9nffmP04PptReOenU8Mbxu7';
const API_URL_TOKEN = '/baiduApi/oauth/2.0/token';
const API_URL = '/baiduApi/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro';
let access_token = '';


async function getToken() {
   const postData = {
    client_id: ACCESS_KEY,
    client_secret: SECRET_KEY,
    grant_type: 'client_credentials'
   };

    const config = {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded' // 注意这里的 Content-Type
        }
    };

    try {
        const response = await axios.post(API_URL_TOKEN, new URLSearchParams(postData).toString(), config);
        
        return response.data.access_token;
    } catch (error) {
        console.error('请求百度引擎API出错:', error);
        return null;
    }
}

 export default async function callVolcengineApi(prompt) {
  if (!access_token) {
    access_token = await getToken();
  }

   const config = {
       headers: {
         'Content-Type': 'application/json'
       }
   };

  const postData = {
    "messages": [
      {
        "role": "user",
        "content": prompt
      },
    ],
    "temperature": 0.95,
    "top_p": 0.8,
    "penalty_score": 1,
    "enable_system_memory": false,
    "disable_search": false,
    "enable_citation": false
  }

   try {
       const response = await axios.post(API_URL + '?access_token=' + access_token, postData, config);
       
       return Promise.resolve(response.data);
   } catch (error) {
       console.error('请求百度引擎API出错:', error);
       return null;
   }
}



